import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:musicapp/model/mv.dart';
import 'package:musicapp/model/recommend.dart';
import 'package:musicapp/utils/navigator_util.dart';
import 'package:musicapp/utils/net_utils.dart';
import 'package:musicapp/widgets/common_text_style.dart';
import 'package:musicapp/widgets/h_empty_view.dart.dart';
import 'package:musicapp/widgets/v_empty_view.dart';
import 'package:musicapp/widgets/widget_banner.dart';
import 'package:musicapp/widgets/widget_future_builder.dart';
import 'package:musicapp/model/banner.dart' as mBanner;
import 'package:musicapp/widgets/widget_play_list.dart';

import '../../../model/album.dart';
import '../../../utils/utils.dart';

class DiscoverPage extends StatefulWidget {
  @override
  _DiscoverPageState createState() => _DiscoverPageState();
}

/// TabBar,TabBarView切换一直保存在内存中, 添加AutomaticKeepAliveClientMixin，并设置为true

class _DiscoverPageState extends State<DiscoverPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _buildBanner(),
            Padding(
              padding: EdgeInsets.symmetric(
                horizontal: ScreenUtil().setWidth(15),
              ),
              child: Column(
                // MainAxisSize：在主轴方向占有空间的值，默认是max。
                // max：根据传入的布局约束条件，最大化主轴方向的可用空间；
                // min：与max相反，是最小化主轴方向的可用空间；
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  VEmptyView(40),
                  _buildHomeCategoryList(),
                  VEmptyView(20),
                  Text('推荐歌单', style: commonTextStyle),
                ],
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(
                horizontal: ScreenUtil().setWidth(15),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  VEmptyView(40),
                  _buildRecommendPlayList(),
                  VEmptyView(20),
                  Text('新碟上架', style: commonTextStyle),
                  VEmptyView(20),
                  _buildNewAlbum(),
                  VEmptyView(20),
                  Text('MV 排行', style: commonTextStyle),
                  VEmptyView(20),
                  _buildTopMv()
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建轮播图
  Widget _buildBanner() {
    return CustomFutureBuilder<mBanner.Banner>(
      futureFunc: NetUtils.getBannerData,
      builder: (context, data) {
        List<String> banner = ['images/myimg/mmexport1572926865761.jpg'];
        banner.addAll(data.banners.map((e) => e.pic).toList());
        return CustomBanner(banner);
      },
    );
  }

  /// 构建分类列表
  Widget _buildHomeCategoryList() {
    Map<String, String> map = {
      '每日推荐': 'images/icon_daily.png',
      '歌单': 'images/icon_playlist.png',
      '排行榜': 'images/icon_rank.png',
      '电台': 'images/icon_radio.png',
      '直播': 'images/icon_look.png',
    };

    List<String> keys = map.keys.toList();
    double width = ScreenUtil().setWidth(100);
    // GridView.count构造函数内部使用了SliverGridDelegateWithFixedCrossAxisCount，我们通过它可以快速的创建横轴固定数量子元素的GridView
    return GridView.custom(
      shrinkWrap: true,
      padding: EdgeInsets.only(bottom: 10),
      // 创建一个委托，在横轴上用固定数量的瓦片进行网格布局。
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        // 该属性表示横轴子元素的数量。
        crossAxisCount: keys.length,
        // 表示横轴方向子元素的间距。
        childAspectRatio: 1 / 1.1,
        // crossAxisSpacing 该属性表示主轴方向的间距。
      ),
      // GestureDetector 生成器
      childrenDelegate: SliverChildBuilderDelegate(
        (context, index) {
          return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                print('点击$index');
                switch (index) {
                  case 0: 
                    NavigatorUtil.goDailySongsPage(context);
                    break;
                  case 1:
                    print('点击$index');
                    break;
                  case 2:
                    NavigatorUtil.goTopListPage(context);
                    break;
                }
              },
              child: Column(
                children: <Widget>[
                  Stack(
                    alignment: Alignment.center,
                    children: <Widget>[
                      Container(
                        width: width,
                        height: width,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(width / 2),
                          border: Border.all(color: Colors.black12, width: 0.5),
                          gradient: RadialGradient(
                            colors: [Color(0xFFFF8174), Colors.red],
                            center: Alignment(-1.7, 0),
                            radius: 1,
                          ),
                          // color: Colors.red,
                        ),
                      ),
                      Image.asset(map[keys[index]],
                          width: width, height: width),
                      Container(
                        padding: EdgeInsets.only(top: 5),
                        child: keys[index] == '每日推荐'
                            ? Text(
                                '${DateUtil.formatDate(DateTime.now(), format: 'dd')}',
                                style: TextStyle(
                                    color: Colors.red,
                                    fontWeight: FontWeight.bold),
                              )
                            : Text(''),
                      ),
                    ],
                  ),
                  VEmptyView(10),
                  Text(
                    '${keys[index]}',
                    style: TextStyle(color: Colors.black87, fontSize: 14),
                  ),
                ],
              ));
        },
        // *生产子元素数量
        childCount: keys.length,
      ),
    );
  }

  /// 构建推荐歌单
  Widget _buildRecommendPlayList() {
    return CustomFutureBuilder<RecommendData>(
        futureFunc: NetUtils.getRecommendData,
        builder: (context, snapshot) {
          List<Recommend> data = snapshot.recommend;
          return Container(
            height: ScreenUtil().setWidth(300),
            child: ListView.separated(
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemCount: data.length,
              separatorBuilder: (context, index) {
                return HEmptyView(ScreenUtil().setWidth(30));
              },
              padding:
                  EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(15)),
              itemBuilder: (context, index) {
                return PlayListWidget(
                  text: data[index].name,
                  picUrl: data[index].picUrl,
                  playCount: data[index].playcount,
                  maxLines: 2,
                  onTap: () {
                    NavigatorUtil.goPlayListPage(context, data: data[index]);
                  },
                );
              },
            ),
          );
        });
  }

  /// 构建新碟上架
  Widget _buildNewAlbum() {
    return CustomFutureBuilder<AlbumData>(
        futureFunc: NetUtils.getAlbumData,
        builder: (contex, snapshot) {
          List<Albums> data = snapshot.albums;
          return Container(
            height: ScreenUtil().setWidth(300),
            child: ListView.separated(
              separatorBuilder: (context, index) {
                return HEmptyView(ScreenUtil().setWidth(30));
              },
              padding:
                  EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(15)),
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemCount: data.length,
              itemBuilder: (context, index) {
                return PlayListWidget(
                  text: data[index].name,
                  picUrl: data[index].picUrl,
                  subText: data[index].artist.name ?? "",
                  maxLines: 1,
                );
              },
            ),
          );
        });
  }

  /// 构建MV 排行榜
  Widget _buildTopMv() {
    return CustomFutureBuilder<MVData>(
        futureFunc: NetUtils.getTopMvData,
        builder: (context, snapshot) {
          var data = snapshot.data;
          return ListView.separated(
            separatorBuilder: (context, index) {
              return VEmptyView(ScreenUtil().setWidth(100));
            },
            padding:
                EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(15)),
            itemBuilder: (context, index) {
              return Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8)),
                    child: Utils.showNetImage(
                      data[index].cover,
                    ),
                  ),
                  VEmptyView(5),
                  Text(
                    data[index].name,
                    style: commonTextStyle,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  VEmptyView(2),
                  Text(data[index].artistName, style: smallGrayTextStyle),
                ],
              );
            },
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: data.length,
          );
        });
  }

  /// 不会被销毁,占内存中
  @override
  bool get wantKeepAlive => true;
}
